package com.shanhy.lixp.need001.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shanhy.lixp.need001.model.Company;

/**
 * HTML解析
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 */
@Service
public class CompanyHtmlParser {

//	private static final Logger logger = LoggerFactory.getLogger(CompanyHtmlParser.class);

	@Autowired
	private CompanyHtmlRequest requestCompanyHtml;

	/**
	 * 读取列表数据HTML
	 *
	 * @return
	 * @author SHANHY
	 * @create 2016年9月3日
	 */
	public String getCompanyListHtml(String pageNum) {
		String pageHtml = requestCompanyHtml.getPageHtml(pageNum);
		if (isCompanyListPage(pageHtml)) {
			// 解析数据
			return pageHtml;
		} else {
			return null;
		}
	}

	/**
	 * 列表
	 *
	 * @param pageNum
	 * @return
	 * @author SHANHY
	 * @create 2016年9月3日
	 */
	public Map<String, Object> getCompanyList(String pageNum) {
		String resultHtml = getCompanyListHtml(pageNum);
		if (resultHtml != null) {
			// HTML解析
			return jsoupCompanyListHtml(resultHtml);
		}
		return null;
	}

	/**
	 * 解析HTML为对象集合
	 *
	 * @param companyListHtml
	 * @return
	 * @author SHANHY
	 */
	public Map<String, Object> jsoupCompanyListHtml(String companyListHtml) {
		Map<String, Object> resultMap = new HashMap<>();
		Document doc = Jsoup.parse(companyListHtml);
		Element dataGrid1 = doc.getElementById("DataGrid1");
		Elements dataTrArr = dataGrid1.getElementsByTag("tr");

		List<Company> companyList = null;
		String totalPage = "";
		Company company = null;
		if (dataTrArr != null) {
			companyList = new ArrayList<Company>();
			for (int i = 0, j = dataTrArr.size(); i < j; i++) {
				if (i == 0)// 第一行是标题
					continue;
				Elements tds = dataTrArr.get(i).getElementsByTag("td");
				company = new Company();
				Element a = tds.get(1).getElementsByTag("a").get(0);
				company.setSname(a.text());
				company.setUrl(a.attr("href"));
				companyList.add(company);
			}
			String temp = doc.getElementsContainingOwnText("末页").get(0).parent().attr("href");
			totalPage = temp.replaceAll("[^\\d]", "");
		}
		resultMap.put("list", companyList);
		resultMap.put("totalPage", totalPage);
		return resultMap;
	}

	/**
	 * 判断获取数据页面是否成功
	 *
	 * @param pageHtml
	 * @return
	 * @author SHANHY
	 */
	private boolean isCompanyListPage(String pageHtml) {
		if (pageHtml != null)
			return pageHtml.contains("FrameAll.aspx");// “查看”按钮的链接
		return false;
	}

}
